/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package exatrez.manager;

import com.google.inject.Inject;
import com.google.inject.Provider;
import exatrez.model.ShipVisitFlow;
import exatrez.stripes.util.EmailUtil;
import freemarker.cache.FileTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import java.io.File;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.hibernate.SessionFactory;
import org.hibernate.StatelessSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Mansur
 */
public class CronVisit3Manager {
    
    private static Logger LOG = LoggerFactory.getLogger(CronVisit3Manager.class);
    
    @Inject
    exatrez.stripes.Configuration conf;
    @Inject
    private EmailUtil emailUtil;
    @Inject
    Provider<SessionFactory> sp;
    
    public void checkAndEmail(){
        LOG.debug("Start...");
        List<String> listStaff = this.getListStaffID();
        LOG.debug("FlowListVisit.size : "+listStaff.size());
        List<Map<String,String>> list = new ArrayList<Map<String, String>>();        
        int total = 0;
        for (String staffId : listStaff) {   
            Map<String,String> rootMap = new HashMap<String, String>();
            int count = this.getListStaffVisit(staffId).size();
            LOG.debug("staffId : "+staffId+", count : "+count);
            rootMap.put("staffid", staffId);
            rootMap.put("total", String.valueOf(count));
            list.add(rootMap);
            total += count;
        }
        if(!list.isEmpty()){
            this.sendMail(list, total);
        }
        LOG.debug("Finish...");
    }
    
    private List<String> getListStaffID(){
        StatelessSession ss = null;
        try{
            ss = sp.get().openStatelessSession();
            return ss.createQuery("SELECT DISTINCT s.user.userId FROM ShipVisit3 s WHERE s.deleted = 'N' AND s.status = 'K' AND s.workflow = 'T' ").list();
        }catch(Exception ex){
            LOG.error("getListStaffID() :", ex);
        }finally{
            ss.close();
        }
        return Collections.EMPTY_LIST;
    }
    
    private List<ShipVisitFlow> getListStaffVisit(String staffId){
        StatelessSession ss = null;
        try{
            ss = sp.get().openStatelessSession();
            return ss.createQuery("SELECT s FROM ShipVisit3 s WHERE s.deleted = 'N' AND s.status = 'K' AND s.workflow = 'T' AND s.user.userId = :userId ").setParameter("userId", staffId).list();
        }catch(Exception ex){
            LOG.error("getListNotVerified() :", ex);
        }finally{
            ss.close();
        }
        return Collections.EMPTY_LIST;
    }
    
    private void sendMail(List<Map<String,String>> list, int total){
        try{
            // freemarker stuff.
                Configuration cfg = new Configuration();
                FileTemplateLoader templateLoader 
                        = new FileTemplateLoader(new File(conf.getProperty("email.template.path")));
                cfg.setTemplateLoader(templateLoader);
                cfg.setObjectWrapper(new DefaultObjectWrapper());
                Template template = cfg.getTemplate("html-sv-coo-cron.ftl");
                Map<String, Object> rootMap = new HashMap<String, Object>();
                rootMap.put("reports", list.toArray());
                rootMap.put("totals", String.valueOf(total));
                rootMap.put("inside", conf.getProperty("task.email.inside"));
                rootMap.put("outside", conf.getProperty("task.email.outside"));
                
                Writer out = new StringWriter();
                template.process(rootMap, out);
                String [] recipient = conf.getProperty("email.ptask.coo").split(",");
                emailUtil.send(recipient, null, "Ship Visit Report : New report from staff's.", out.toString(), "text/html");
        }catch(Exception ex){
            LOG.error("error occured {}!! ", ex);
        }
    }
    
}
